package cn.quizs.game;

import com.corundumstudio.socketio.AuthorizationListener;
import com.corundumstudio.socketio.Configuration;
import com.corundumstudio.socketio.HandshakeData;
import com.corundumstudio.socketio.SocketIOServer;
import com.corundumstudio.socketio.annotation.SpringAnnotationScanner;
import com.corundumstudio.socketio.store.RedissonStoreFactory;
import org.redisson.Redisson;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

import java.util.List;

@SpringBootApplication
public class QuizGameApplication {

	@Value("${wss.server.host}")
	private String host;

	@Value("${wss.server.port}")
	private Integer port;


	@Bean
	public SocketIOServer socketIOServer()
	{
		Configuration config = new Configuration();
		config.setHostname(host);
		config.setPort(port);


		Config redissonConfig = new Config();
		redissonConfig.useSingleServer().setAddress("redis://127.0.0.1:6379");
		final Redisson redisson = (Redisson) Redisson.create(redissonConfig);
		RedissonStoreFactory redisStoreFactory = new RedissonStoreFactory(redisson);

		config.setStoreFactory(redisStoreFactory);


		//该处可以用来进行身份验证
		config.setAuthorizationListener(new AuthorizationListener() {
			@Override
			public boolean isAuthorized(HandshakeData data) {
				//http://localhost:8081?username=test&password=test
				//例如果使用上面的链接进行connect，可以使用如下代码获取用户密码信息，本文不做身份验证
//				String username = data.getSingleUrlParam("username");
//				String password = data.getSingleUrlParam("password");
				return true;
			}
		});


		final SocketIOServer server = new SocketIOServer(config);
		return server;
	}

	@Bean
	public SpringAnnotationScanner springAnnotationScanner(SocketIOServer socketServer) {
		return new SpringAnnotationScanner(socketServer);
	}



	public static void main(String[] args) {
		SpringApplication.run(QuizGameApplication.class, args);
	}
}
